var root = "/";
var xmlHttp;
var debug = false;
var fulldebug = false;
var sent = false;
var data; // inicializa los campos que van a ser parceados
var redireccion; // inicializa redireccion por si se pide del post
var loadingMsg = "Cargando...";
var sendingMsg = "Enviando...";
var successMsg = 'Mensaje Enviado!';
var badMsg = "Verifique campos en rojo";

// ----------------- AJAX ------------------- //

function GetXmlHttpObject(){var xmlHttp=null;try{xmlHttp=new XMLHttpRequest();}catch(e){try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}}return xmlHttp;}

///////////////////// VALIDAR ////////////////////////

function validar(campos,mode,url,up){

	if(sent) return false;
	popup(loadingMsg,'hold','no');
	xmlHttp=GetXmlHttpObject();
	
	if (xmlHttp==null){
		alert ('Tu explorador no soporta AJAX.');
		return;
	} 
	
	if(url) {
	redireccion = url;
	}else {
	redireccion = 0;
	}
		
	data = document.getElementById(campos).value;
	data = data.split(',');
	var params = parseParams(data);
	
	xmlHttp.onreadystatechange = doValidar;
	xmlHttp.open("POST",root+'validate.php?mode='+mode,true);
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.setRequestHeader("Content-length",params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params);
	
}
function doValidar(){ 

var errores = 0;

	if (xmlHttp.readyState==4){
	
		//$('html, body').animate({scrollTop:0}, 1500);

		var r = xmlHttp.responseText;

		// debug
		if(debug == true) alert(r);
		if(debug == true && redireccion!=0) alert('redireccionar a la url: '+redireccion+' si es que todos los campos estan validados.');
		
		var x = 0;
		var f = new Array();
		
		for(i in data){
			f[x] = r.substr(x,1);
			
			// fulldebug
			if(fulldebug == true) alert('campo numero:'+f[x]);
			
			validate(f[x],data[i]);
			x++;
		}
		
		for(i in f){
			if(f[i] == '0') errores++;
		}
		
		// fulldebug
		if(fulldebug == true) alert('errores='+errores);
				
		if(errores > 0){
			popup(badMsg,'fade','no');
		}else{
			sent = true;
			popup(sendingMsg,'hold','no');
			//if(mode=='registro') $('.bt-registrar').html("Usuario Registrado!");
			popup(successMsg,'fade','no');
			if(redireccion!=0) redir(redireccion,5000);
		}
	
	}

}

///////////////////// POPUP ////////////////////////

function popup(msg,unblock,red){
if(unblock=='click') msg = msg + ' (Click para continuar) ';
$.blockUI({ 
message: msg.replace(/\n/gi,'<br/>'),
css: {
border:'none', padding:'15px', size:'12.0pt',
backgroundColor:'#000', color:'#fff',
opacity:'.8','-webkit-border-radius': '10px','-moz-border-radius': '10px'
}
});
if(unblock=='hold'){
// algo adicional para el holding
}
if(unblock=='fade'){
window.setTimeout($.unblockUI, 4500);
//$(document).bind('click', function() {
//window.setTimeout($.unblockUI, 1);
//if(red=='si' && unblock!='hold') redir('',100);
//});
if(red=='si' && unblock!='hold') redir('',5000);
}
if(unblock=='click'){
$(document).bind('click', function() {
window.setTimeout($.unblockUI, 1);
redir('',500);
});
if(red=='si' && unblock!='hold' && unblock!='click') redir('',500);
}
}

////////////////// COLOREA CAMPOS ///////////////////////////

// validate estilo de campos
function validate(status,id){
if(status == 0){
$("#"+id).css('color','#ffffff');
$("#"+id).css('background','#f90000');
}else{
$("#"+id).css('color','#000000');
$("#"+id).css('background','#ffffff')
}
}

//////////////////// PARSER /////////////////////////

// parser
function parseParams(params){
var contenedor = '';
for(var contar in params){
var type = gettype(params[contar]);
if(type == 'checkbox' || type == 'radio'){
contenedor += params[contar]+'='+getcheck(params[contar])+'&';
}else if(type == 'select-multiple'){
contenedor += params[contar]+'='+getMultiple(params[contar])+'&';
}else{
contenedor += params[contar]+'='+escape(getval(params[contar]))+'&';
}
}
return contenedor.substr(0,contenedor.length-1);
}

// Get And Sets
function setval(id,val){
document.getElementById(id).value = val;
}
function getval(id){
return document.getElementById(id).value;
}
function getcheck(id){
return document.getElementById(id).checked;
}
function gettype(id){
return document.getElementById(id).type;
}
function getMultiple(ob){
ob = document.getElementById(ob);
selected = new Array();
for(var i = 0; i < ob.options.length; i++) if(ob.options[i].selected) selected.push(ob.options[i].value);
return selected;
}

///////////////// REDIR ////////////////////////////

// redir
function redir(url,timeout){
	setTimeout('doRedir(\''+url+'\')',timeout);
}
// do redir
function doRedir(url){
	window.location = url;
}